import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes=[
    {
        path:'/',
        name:'login',
        component:()=>import('../components/Login.vue')
    },
    {
        path: '/',
        name: '/',
        redirect: '/login',
        //redirect   表示当路径使用到‘/’是，就自动跳转到路径为‘/login’
    },
    {
        path:'/Index',
        name:'index',
        meta: {
            requireAuth: true // 添加该字段，表示进入这个路由是需要登录的
        },
        component:()=>import('../components/Index.vue'),
        children:[
            {
                path:'/Home',
                name:'home',
                meta:{
                    title:"首页"
                },
                component:()=>import('../components/Home.vue'),
            },
        ]
    },
]
const router = new VueRouter({
    mode:'history',
    routes
})

//全局前置守卫
router.beforeEach((to, from, next) => {
    // to and from are both route objects. must call `next`.
    if (to.path === '/login' || to.path === '/') {
        next();//直接放行
    } else {
        const token = sessionStorage.getItem('token');
        if (token === null || token === '') {
            next('/')
        } else {
            next()
        }
    }
})

export function resetRouter() {
    router.matcher = new VueRouter({
        mode:'history',
        routes: []
    }).matcher
}

const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (to) {
    return VueRouterPush.call(this, to).catch(err => err)
}


export default router;
